package com.studiofortress.sf.util.structure;

import com.studiofortress.sf.structure.Actor;
import com.studiofortress.sf.graphics.GraphicsGL;
import java.awt.Color;

/**
 * This is an Frames Per Second counter that counts
 * how many frames have occured over a second and
 * then updates it's image to display that information.
 * 
 * @author Joseph Lenton
 * @version 02/08/2008
 */
public class FPSActor<G extends GraphicsGL> extends Actor<G>
{
    private int fps;
    private int count;
    private long time;
    
    /**
     * Trivial constructor.
     */
    public FPSActor()
    {
        fps = 0;
        count = 0;
        time = System.currentTimeMillis() + 1000;
    }

    @Override
    protected void addedToWorld()
    {
        // ensure this is ontop of ALL Actors
        getWorld().setPaintOrder(this, Integer.MAX_VALUE);
    }
    
    /**
     * Increments the FPS counter an once a second updates it's
     * image with the latest count.
     */
    @Override
    public void act() 
    {
        ++count;
        if (time < System.currentTimeMillis()) {
            fps = count;
            count = 0;
            time = System.currentTimeMillis() + 1000;
        }
    }

    @Override
    public void paint(G g)
    {
        g.setColor(Color.RED);
        g.drawString("fps: " + fps, 5, 20);
    }
    
    /**
     * @return The current count of frames per second.
     */
    public int getFPS()
    {
        return fps;
    }
}
